import uuid
from datetime import datetime

from flask import Blueprint, render_template, request, jsonify, session,redirect,url_for
from flask_login import login_required
from sqlalchemy import and_
from werkzeug.security import generate_password_hash

from applications.common import curd
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id, enable, disable
from applications.common.helper import ModelFilter
from applications.common.utils.getopenid import get_openid, token
from applications.common.utils.http import table_api, success_api, fail_api, wxuser_success_api, coupon_api, stores_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.exts import db
from applications.exts.cache import cache
from applications.models import Role, Power, User, CouponUser, Coupon, Store, Coupon_Class
from applications.models.wx_user import WxUser
from applications.schemas import RoleOutSchema, PowerOutSchema2, WxUserOutSchema, CouponUserOutSchema, CouponOutSchema
from applications.common.utils import upload as upload_curd
from applications.schemas.stores import StoresOutSchema

wxstores = Blueprint('wxstores', __name__, url_prefix='/wxstores')


# ========web=======
@wxstores.route('/')
@login_required
def main():
    return render_template('store/main.html')


#   查询
@wxstores.route('/data')
@login_required
# @authorize("admin:user:main", log=True)
def data():
    # 获取请求参数
    storesname = xss_escape(request.args.get('storesname', type=str))
    # 查询参数构造
    mf = ModelFilter()
    if storesname:
        mf.contains(field_name="title", value=storesname)

    # if dept_id:
    #     mf.exact(field_name="dept_id", value=dept_id)
    # orm查询

    # 使用分页获取data需要.items
    stores = Store.query.filter(and_(mf.get_filter(model=Store), Store.is_del == 0)).layui_paginate()
    count = stores.total
    # 返回api
    return table_api(data=model_to_dicts(schema=StoresOutSchema, data=stores.items), count=count)


# 优惠卷
@wxstores.route('/add')
@login_required
# @authorize("admin:user:add", log=True)
def add():
    # coupons = Store.query.filter().all()
    lng=session.get('lng')
    lat = session.get('lat')
    return render_template('store/add.html', lng=lng,lat=lat)


# add
@wxstores.route('/addstores', methods=["POST"])
@login_required
# @authorize("admin:user:add", log=True)
def addstores():
    req_json = request.json

    # {'nume': '1', 'lngname': '116.005282', 'latname': '39.901496', 'shopcontent': '1', 'shopslogan': '1',
    #  'file': 'http://127.0.0.1:5000/static/upload/useravatar/dec6ea62-1543-4a2c-9faa-d7bb9e2fb5a4.88.png'}

    print('req_json:', req_json)

    name = xss_escape(req_json.get('name'))
    lngname = xss_escape(req_json.get('lngname'))
    latname = xss_escape(req_json.get('latname'))
    shopcontent = xss_escape(req_json.get('shopcontent'))
    shopslogan = xss_escape(req_json.get('shopslogan'))
    file = xss_escape(req_json.get('file'))

    store = Store()
    store.title=name
    store.latitude=latname
    store.longitude=lngname
    store.content=shopcontent
    store.slogan=shopslogan
    store.iconPath=file


    #
    try:
        db.session.add(store)
        db.session.commit()
        return success_api(msg="添加成功")
    except Exception as e:
        print(e)
        db.session.rollback()
        return fail_api(msg="添加失败")


@wxstores.route('/addmap', methods=["POST", "GET"])
@login_required
def addmap():
    if request.method == "POST":
        lng = request.form.get('lng')
        lat = request.form.get('lat')
        print(1111)
        session['lng'] = lng
        session['lat'] = lat
        print(lat, lng)
        print(session.get('lat'))
        # return redirect(url_for('user_api.addstore'))
        msg = {'ststus': 0, 'msg': '选择成功'}
        return jsonify(msg)
        # return redirect(url_for('wxstores.add'))
    else:
        return render_template('store/maplist.html')


@wxstores.route('/upload', methods=["POST"])
@login_required
def upphoto():
    if 'file' in request.files:
        photo = request.files['file']
        mime = request.files['file'].content_type
        print(photo)
        file_url = upload_curd.upfile(file=photo, flag=1)
        print(file_url)
        file_url = request.host_url + file_url
        print('file_url:', file_url)
        res = {
            "msg": "上传成功",
            "code": 0,
            "success": True,
            "data":
                {"src": file_url}
        }
        return jsonify(res)
    return fail_api()




# 启用
@wxstores.route('/enable', methods=["PUT"])
@login_required
# @authorize("admin:role:edit", log=True)
def enables():
    id = request.json.get('gid')
    if id:
        res = enable(Store, id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启动成功")
    return fail_api(msg="数据错误")


# 禁用
@wxstores.route('/disable', methods=["PUT"])
@login_required
# @authorize("admin:role:edit", log=True)
def dis_enable():
    _id = request.json.get('gid')
    if _id:
        res = disable(Store, _id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")


# 删除
@wxstores.route('/remove/<int:id>', methods=["DELETE"])
@login_required
# @authorize("admin:user:remove", log=True)
def delete(id):
    store = Store.query.filter_by(id=id).first()
    if store:
        store.is_del=1
        try:
            db.session.commit()
            return success_api(msg="删除成功")
        except Exception as e:
            print(e)
            return fail_api(msg="删除失败")
    else:
        return fail_api(msg="删除失败")


# 批量删除
@wxstores.route('/batchRemove', methods=["DELETE"])
@login_required
# @authorize("admin:user:remove", log=True)
def batch_remove():
    flag=0
    ids = request.form.getlist('ids[]')
    for id in ids:
        store = Store.query.filter_by(id=id).first()
        if store:
            store.is_del=1
            try:
                db.session.commit()
                flag=1
            except Exception as e:
                print(e)
                flag=0
    if flag==1:
        return success_api(msg="批量删除成功")
    else:
        return fail_api(msg="批量删除失败")

# =======wx微信=======

@wxstores.route('/shopslist', methods=["POST","GET"])
def shopslist():
    stores=Store.query.filter(Store.is_del==0).all()
    return stores_api(stores=model_to_dicts(StoresOutSchema,data=stores))
